package com.hspedu.poly_.polyarr;

/**
 * @Author Stringzhua
 * @Date 2024/3/2 19:53
 * description:
 */
public class polyarr {
    public static void main(String[] args) {
        //创建1个person对象
        //2个Student对象和2个Teacher对象,统一防在数组中,并调用每个对象say方法

        Person[] persons=new Person[5];//创建对象数组
        persons[0]=new Person("jack",20);
        persons[1]=new Student("marry",20,100);
        persons[2]=new Student("smith",19,30);
        persons[3]=new Teacher("scott",30,20000);
        persons[4]=new Teacher("king",50,25000);

        //循环遍历多态数组,调用say方法
        for (int i = 0; i < persons.length; i++) {
            //person[i] 编译类型是Person 运行类型是根据实际情况由JVM来判断
            persons[i].say();//动态绑定机制
            System.out.println(persons[i].say());
//            persons[i].teach();
//            persons[i].study();
            //这里使用instanceof
            //判断person[i]的运行类型是不是Student
            if(persons[i] instanceof Student){
                Student student=(Student) persons[i];//向下转型
                student.study();
//                ((Student)persons[i]).study();//也可以这么写
            }else if(persons[i] instanceof Teacher){
                ((Teacher) persons[i]).teach();
            }else {
                System.out.println("你的类型有误~请检查！");
            }
        }
    }
}
